import 'dart:io';

import 'package:path_provider/path_provider.dart';

class FileSaveUtils {
  static const String fileDir = "trace";
  static const String fileName = "trace.log";
  static Future<String> getFileSavePath() async {
    String actualSavePath = "";
    if (Platform.isAndroid) {
      /// 获取Android的存储路径
      var supportDir = await getApplicationSupportDirectory();
      actualSavePath = supportDir.path + Platform.pathSeparator + fileDir;
    } else if (Platform.isIOS) {
      /// 获取iOS的存储路径
      var supportDir = await getApplicationSupportDirectory();
      actualSavePath = supportDir.path + Platform.pathSeparator + fileDir;
    } else {
      throw UnsupportedError("platform is not support...");
    }
    var absPath = actualSavePath + Platform.pathSeparator + fileName;
    var dir = Directory(actualSavePath);
    if (!dir.existsSync()) {
      dir.createSync();

      File file = File(absPath);
      if (!file.existsSync()) {
        file.createSync();
      }
    }
    return absPath;
  }

  static Future<String> readFile() async {
    var filePath = await getFileSavePath();

    /// file read...
    File file = File(filePath);
    RandomAccessFile raf = file.openSync();
    raf.lockSync(FileLock.blockingShared);
    String content = file.readAsStringSync();
    raf.unlockSync();
    return content;
  }

  /// 删除原有文件，创建新文件
  static Future<void> deleteAndCreate() async {
    var filePath = await getFileSavePath();
    File file = File(filePath);
    RandomAccessFile raf = file.openSync();
    raf.lockSync(FileLock.blockingShared);
    file.deleteSync();
    file.createSync();
    raf.unlockSync();
  }
}
